package site.edody.dframe.websocket;


import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;


import java.io.IOException;

@Component
@ServerEndpoint("/dframe/ws/{sid}")
public class WebSocketServer {


    private final static Logger log = LoggerFactory.getLogger(WebSocketServer.class);

    //与设备终端的连接
    private Session session;
    private String sid;

    private WebSocketListener listener;



    @OnOpen
    public void onOpen(Session session,@PathParam("sid") String sid) {
        this.session = session;
        this.sid = sid;
        try {
            WebSocketCache.getInstance().setWebSocketServer(sid,this);
            setListener((WebSocketListener) Class.forName(WebSocketCache.getInstance().getListenerClass()).getDeclaredConstructor().newInstance());
            listener.onOpen(sid);
        } catch (Exception e) {
            log.error("websocket IO异常",e);
        }
    }


    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
//        //从cache中删除
        WebSocketCache.getInstance().remove(sid);
        listener.onClose(sid);
        log.debug("有一连接关闭！" + sid);
    }

    /**
     * 收到客户端消息后调用的方法
     * @param message 客户端发送过来的消息
     **/
    @OnMessage
    public void onMessage(String message, Session session) {
//        log.info("收到来自窗口"+sid+"的信息:"+message);

        try {
            listener.onMessage(sid,message);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //群发消息

    }

    /**
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误",error);
        listener.onError(sid,error);
//        error.printStackTrace();
    }



    /**
     * 实现服务器主动推送
     */
    public void sendMessage( String message) throws IOException {
        log.debug("准备下发消息："+message);
        session.getBasicRemote().sendText(message);
    }


    public void remove () throws IOException {
        try{
            session.close();
            WebSocketCache.getInstance().remove(sid);
        }catch (IOException e){
            throw e;
        } finally {
            session = null;
        }

    }

    public void setListener(WebSocketListener listener) {
        this.listener = listener;
    }
}
